<template>
  <div class="video-mix-generate">
    <div class="header">
      <div class="section-header">
        <h1 class="section-title">生成混剪视频</h1>
        <h2 class="section-title records-title" @click="handleGoToRecords">
          <el-icon><Document /></el-icon>
          生成记录
        </h2>
      </div>
    </div>

    <div class="main-content">
      <!-- 基本信息 -->
      <div class="section">
        <h2 class="section-title">基本信息</h2>
        <div class="form-content">
          <el-form :model="formData" label-position="top">
            <el-form-item label="产品名称">
              <el-input v-model="formData.productName" placeholder="请输入产品名称" />
            </el-form-item>
            <el-form-item label="产品特点">
              <el-input
                v-model="formData.productFeatures"
                type="textarea"
                :rows="4"
                placeholder="请输入产品特点，每行一个特点"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 视频上传 -->
      <div class="section">
        <h2 class="section-title">上传视频素材</h2>
        <div class="upload-content">
          <el-upload
            class="video-uploader"
            :action="uploadAction"
            :auto-upload="false"
            :on-change="handleVideoChange"
            :on-remove="handleVideoRemove"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :headers="uploadHeaders"
            :data="uploadData"
            :show-file-list="false"
            multiple
            accept="video/*"
            :limit="10"
            drag
            ref="uploadRef"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将视频拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持mp4、mov等格式视频文件，单个文件不超过500MB
              </div>
            </template>
          </el-upload>

          <!-- 视频预览区域 -->
          <div class="preview-grid" v-if="videoList.length > 0">
            <div v-for="(file, index) in videoList" :key="index" class="video-card">
              <!-- 视频预览 -->
              <div class="video-thumbnail" v-if="file.raw.type.startsWith('video/')">
                <video
                  class="preview-video"
                  :src="file.url"
                  muted
                  loop
                  preload="metadata"
                  @mouseenter="handlePreviewMouseOver(file)"
                  @mouseleave="handlePreviewMouseOut(file)"
                ></video>
                <div class="video-overlay" v-if="file.uploading">
                  <el-progress type="circle" :percentage="file.uploadProgress || 0"></el-progress>
                  <span class="upload-text">上传中...</span>
                </div>
                <div class="video-overlay error-overlay" v-else-if="file.error">
                  <el-icon size="32" class="error-icon"><Close /></el-icon>
                  <span class="error-text">上传失败</span>
                </div>
                <div class="video-overlay success-overlay" v-else-if="file.fileId">
                  <el-icon size="24" class="success-icon"><Check /></el-icon>
                </div>
              </div>
              <!-- 图片预览 -->
              <div class="video-thumbnail" v-else-if="file.raw.type.startsWith('image/')">
                <img
                  class="preview-image"
                  :src="file.url"
                  alt="预览图片"
                />
                <div class="video-overlay" v-if="file.uploading">
                  <el-progress type="circle" :percentage="file.uploadProgress || 0"></el-progress>
                  <span class="upload-text">上传中...</span>
                </div>
                <div class="video-overlay error-overlay" v-else-if="file.error">
                  <el-icon size="32" class="error-icon"><Close /></el-icon>
                  <span class="error-text">上传失败</span>
                </div>
                <div class="video-overlay success-overlay" v-else-if="file.fileId">
                  <el-icon size="24" class="success-icon"><Check /></el-icon>
                </div>
              </div>
              
              <!-- 卡片信息 -->
              <div class="video-info">
                <div class="video-name" :title="file.name">{{ file.name }}</div>
                <div class="video-status" :class="{ 
                  'uploading': file.uploading, 
                  'success': file.fileId, 
                  'error': file.error 
                }">
                  {{ getFileStatus(file) }}
                </div>
              </div>
              
              <!-- 卡片操作 -->
              <div class="video-actions">
                <el-button
                  v-if="file.error"
                  type="primary"
                  size="small"
                  @click="retryUpload(file)"
                >
                  重试
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  @click="handleVideoRemove(file)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>

          <!-- 图片预览弹窗 -->
          <el-dialog
            v-model="previewImageVisible"
            :title="currentPreviewFile?.name"
            width="80%"
            class="preview-dialog"
            append-to-body
          >
            <div class="preview-dialog-content">
              <img :src="currentPreviewFile?.url" class="preview-dialog-image" />
            </div>
          </el-dialog>
        </div>
      </div>

      <!-- 数字人和音色选择 -->
      <div class="section">
        <h2 class="section-title">数字人和音色设置</h2>
        <div class="form-content">
          <el-form :model="formData" label-position="top">
            <el-form-item label="选择数字人">
              <div class="select-trigger" @click="openAvatarDialog">
                <div v-if="formData.digitalHuman" class="selected-option">
                  <img :src="getSelectedDigitalHuman.avatar" class="digital-human-avatar" />
                  <span>{{ getSelectedDigitalHuman.label }}</span>
                </div>
                <div v-else class="placeholder">
                  请选择数字人
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="选择音色">
              <div class="select-trigger" @click="showVoiceDialog = true">
                <div v-if="formData.voice" class="selected-option">
                  <span>{{ getSelectedVoice.label }}</span>
                </div>
                <div v-else class="placeholder">
                  请选择音色
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 数字人选择弹窗 -->
      <el-dialog
        v-model="showAvatarDialog"
        title="选择数字人"
        width="80%"
        class="avatar-dialog"
      >
        <div class="avatar-filter">
          <!-- 人种筛选 -->
          <div class="ethnicity-filter">
            <label class="filter-label">人种筛选：</label>
            <div class="ethnicity-list">
              <!-- 如果正在加载或人种列表为空，显示加载中 -->
              <div v-if="ethnicityLoading || ethnicityList.length === 0" class="ethnicity-item disabled">
                {{ ethnicityLoading ? '加载中...' : '暂无人种分类' }}
              </div>
              <!-- 所有分类选项 -->
              <div 
                v-if="ethnicityList.length > 0"
                class="ethnicity-item"
                :class="{ active: activeEthnicity === 'all' }"
                @click="handleEthnicityChange('all')"
              >
                所有
              </div>
              <!-- 人种列表 -->
              <div 
                v-for="ethnicity in ethnicityList" 
                :key="ethnicity.ethnicityId" 
                class="ethnicity-item"
                :class="{ active: activeEthnicity === ethnicity.ethnicityId }"
                @click="handleEthnicityChange(ethnicity.ethnicityId)"
              >
                {{ ethnicity.ethnicityName }}
              </div>
            </div>
          </div>
        </div>
        
        <div class="avatar-grid" ref="avatarGridRef" @scroll="handleAvatarScroll">
          <div
            v-for="avatar in filteredAvatarList"
            :key="avatar.aiavatarId"
            class="avatar-card"
            :class="{ active: selectedAvatar?.aiavatarId === avatar.aiavatarId }"
            @click="handleSelectAvatar(avatar)"
          >
            <div class="avatar-image-wrapper">
              <video
                v-if="avatar.previewVideoUrl && avatar.isPlaying"
                :src="avatar.previewVideoUrl"
                class="avatar-video"
                preload="metadata"
                muted
                loop
                autoplay
                :ref="el => { if (el) previewVideoRefs[avatar.aiavatarId] = el }"
                @click="pauseVideo(avatar)"
              ></video>
              <img
                v-else
                :src="avatar.coverUrl || avatar.previewVideoUrl"
                class="avatar-cover"
                :alt="avatar.aiavatarName"
                @click="avatar.previewVideoUrl ? playVideo(avatar) : handleSelectAvatar(avatar)"
                @error="onImageError($event, avatar)"
              />
              <div class="play-overlay" v-if="avatar.previewVideoUrl && !avatar.isPlaying" @click="playVideo(avatar)">
                <el-icon class="play-icon"><VideoPlay /></el-icon>
              </div>
              <div class="pause-overlay" v-if="avatar.previewVideoUrl && avatar.isPlaying" @click="pauseVideo(avatar)">
                <el-icon class="pause-icon"><VideoPause /></el-icon>
              </div>
            </div>
            <div class="avatar-info" @click="handleSelectAvatar(avatar)">
              <div class="avatar-name">{{ avatar.aiavatarName }}</div>
              <div class="avatar-tags">
                <el-tag size="small" :type="avatar.gender === 'male' ? 'info' : 'danger'">
                  {{ avatar.gender === 'male' ? '男性' : '女性' }}
                </el-tag>
              </div>
            </div>
          </div>
          <div v-if="avatarLoading" class="loading-more">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>
        </div>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showAvatarDialog = false">取消</el-button>
            <el-button type="primary" @click="confirmAvatarSelection">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 音色选择弹窗 -->
      <el-dialog
        v-model="showVoiceDialog"
        title="选择AI音色"
        width="80%"
        class="voice-dialog"
      >
        <div class="voice-filter">
          <el-radio-group v-model="genderFilter" class="filter-item" @change="handleVoiceFilterChange">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="male">男声</el-radio-button>
            <el-radio-button label="female">女声</el-radio-button>
          </el-radio-group>
          <el-radio-group v-model="ageFilter" class="filter-item" @change="handleVoiceFilterChange">
            <el-radio-button label="">全部年龄</el-radio-button>
            <el-radio-button label="Young">青年</el-radio-button>
            <el-radio-button label="Middle Age">中年</el-radio-button>
            <el-radio-button label="Old">老年</el-radio-button>
          </el-radio-group>
          <el-select v-model="languageFilter" placeholder="全部语言" class="filter-item language-select" style="width: 220px;" @change="handleVoiceFilterChange">
            <el-option label="全部" value="" />
            <el-option label="简体中文 (Simplified Chinese)" value="zh-CN" />
            <el-option label="English" value="en" />
            <el-option label="Arabic (العربية)" value="ar" />
            <el-option label="Bulgarian (Български)" value="bg" />
            <el-option label="Croatian (Hrvatski)" value="hr" />
            <el-option label="Czech (Čeština)" value="cs" />
            <el-option label="Danish (Dansk)" value="da" />
            <el-option label="Dutch (Nederlands)" value="nl" />
            <el-option label="Filipino (Filipino)" value="fil" />
            <el-option label="Finnish (Suomi)" value="fi" />
            <el-option label="French (Français)" value="fr" />
            <el-option label="German (Deutsch)" value="de" />
            <el-option label="Greek (Ελληνικά)" value="el" />
            <el-option label="Hindi (हिन्दी)" value="hi" />
            <el-option label="Hungarian (Magyar)" value="hu" />
            <el-option label="Indonesian (Bahasa Indonesia)" value="id" />
            <el-option label="Italian (Italiano)" value="it" />
            <el-option label="Japanese (日本語)" value="ja" />
            <el-option label="Korean (한국어)" value="ko" />
            <el-option label="Malay (Bahasa Melayu)" value="ms" />
            <el-option label="Norwegian (Norsk)" value="nb" />
            <el-option label="Polish (Polski)" value="pl" />
            <el-option label="Portuguese (Português)" value="pt" />
            <el-option label="Romanian (Română)" value="ro" />
            <el-option label="Russian (Русский)" value="ru" />
            <el-option label="Slovak (Slovenčina)" value="sk" />
            <el-option label="Spanish (Español)" value="es" />
            <el-option label="Swedish (Svenska)" value="sv" />
            <el-option label="Traditional Chinese (繁體中文)" value="zh-Hant" />
            <el-option label="Turkish (Türkçe)" value="tr" />
            <el-option label="Ukrainian (Українська)" value="uk" />
            <el-option label="Vietnamese (Tiếng Việt)" value="vi" />
          </el-select>
        </div>
        
        <div class="voice-grid" ref="voiceGridRef" @scroll="handleVoiceScroll">
          <div
            v-for="voice in filteredVoiceList"
            :key="voice.voiceId"
            class="voice-card"
            :class="{ active: selectedVoice?.voiceId === voice.voiceId }"
            @click="handleSelectVoice(voice)"
          >
            <div class="voice-info">
              <div class="voice-name">{{ voice.voiceName }}</div>
              <div class="voice-tags">
                <el-tag size="small" :type="voice.gender === 'male' ? 'info' : 'danger'">
                  {{ voice.gender === 'male' ? '男声' : '女声' }}
                </el-tag>
                <el-tag size="small" type="warning">{{ voice.age }}</el-tag>
                <el-tag size="small" type="success">{{ voice.accent }}</el-tag>
              </div>
            </div>
            <div class="voice-preview">
              <el-button 
                type="primary" 
                size="small"
                class="preview-btn" 
                @click.stop="playVoiceDemo(voice)"
              >
                <el-icon><VideoPlay /></el-icon>
                试听
              </el-button>
            </div>
          </div>
          <div v-if="voiceLoading" class="loading-more">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>
        </div>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="closeVoiceDialog">取消</el-button>
            <el-button type="primary" @click="confirmVoiceSelection">
              确定
            </el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 操作按钮 -->
      <div class="actions">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting" class="generate-btn">
          开始生成
          <span class="points-text">10积分</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Delete, UploadFilled, ArrowRight, VideoPlay, Loading, VideoPause, ZoomIn, Close, Check, User, Document } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { apiRequest, API_CONFIG } from '../../config/api.js'
import axios from 'axios'

const router = useRouter()
const uploadAction = ref('')
const uploadHeaders = ref({})
const uploadData = ref({})

// 表单数据
const formData = reactive({
  productName: '',
  productFeatures: '',
  digitalHuman: null,
  voice: null
})

// 视频列表
const videoList = ref([])
const submitting = ref(false)
const uploadRef = ref(null)

// 弹窗控制
const showAvatarDialog = ref(false)
const showVoiceDialog = ref(false)

// 数字人相关
const avatarList = ref([])
const selectedAvatar = ref(null)
const avatarLoading = ref(false)
const avatarPageNo = ref(1)
const avatarHasMore = ref(true)

// 人种相关
const ethnicityList = ref([])
const activeEthnicity = ref('all')
const ethnicityLoading = ref(false)

// 音色相关
const voiceList = ref([])
const selectedVoice = ref(null)
const voiceLoading = ref(false)
const voicePageNo = ref(1)
const voiceHasMore = ref(true)
const genderFilter = ref('')
const ageFilter = ref('')
const languageFilter = ref('zh-CN')
const audioPlayer = ref(new Audio())

// 预览相关的状态
const previewVideoRefs = ref({})
const previewImageVisible = ref(false)
const currentPreviewFile = ref(null)

// 计算属性：过滤后的数字人列表
const filteredAvatarList = computed(() => {
  return avatarList.value
})

// 计算属性：过滤后的音色列表
const filteredVoiceList = computed(() => {
  let result = voiceList.value
  
  if (genderFilter.value) {
    result = result.filter(voice => voice.gender === genderFilter.value)
  }
  
  return result
})

// 计算属性：获取选中的数字人信息
const getSelectedDigitalHuman = computed(() => {
  if (formData.digitalHuman) {
    return {
      avatar: formData.digitalHuman.coverUrl || formData.digitalHuman.previewImageUrl || formData.digitalHuman.avatar || '',
      label: formData.digitalHuman.aiavatarName || formData.digitalHuman.name || '未知数字人'
    }
  }
  return null
})

// 计算属性：获取选中的音色信息
const getSelectedVoice = computed(() => {
  if (formData.voice) {
    return {
      label: formData.voice.voiceName || formData.voice.name || '未知音色'
    }
  }
  return null
})

// 获取数字人列表
async function getAvatarList(isLoadMore = false) {
  if (!isLoadMore) {
    avatarPageNo.value = 1
    avatarHasMore.value = true
    avatarList.value = []
  }

  if (!avatarHasMore.value || avatarLoading.value) return

  try {
    avatarLoading.value = true
    console.log('获取数字人列表，页码:', avatarPageNo.value)
    
    const params = new URLSearchParams({
      pageNo: String(avatarPageNo.value),
      pageSize: '20'
    })
    
    // 添加人种参数
    if (activeEthnicity.value && activeEthnicity.value !== 'all') {
      params.append('ethnicityIdList', activeEthnicity.value)
    }
    
    const response = await apiRequest(`/aiAvatar/aiavatarList?${params.toString()}`, {
      method: 'GET'
    })

    if (response && response.code === 200 && response.data) {
      const { data, total } = response.data
      console.log('获取到数字人数据:', data.length, '条，总数:', total)
      
      // 初始化播放状态
      const processedData = data.map(avatar => ({
        ...avatar,
        isPlaying: false,
        error: false
      }))
      
      if (isLoadMore) {
        avatarList.value = [...avatarList.value, ...processedData]
      } else {
        avatarList.value = processedData
      }

      // 判断是否还有更多数据
      avatarHasMore.value = avatarList.value.length < total
      if (avatarHasMore.value) {
        avatarPageNo.value++
      }
      
      console.log('当前数字人列表长度:', avatarList.value.length)
    }
  } catch (error) {
    console.error('获取数字人列表失败:', error)
    ElMessage.warning('获取数字人列表失败')
  } finally {
    avatarLoading.value = false
  }
}

// 获取音色列表
async function getVoiceList(isLoadMore = false) {
  if (!isLoadMore) {
    voicePageNo.value = 1
    voiceHasMore.value = true
    voiceList.value = []
  }

  if (!voiceHasMore.value || voiceLoading.value) return

  try {
    voiceLoading.value = true
    const params = {
      pageNo: voicePageNo.value,
      pageSize: 20
    }
    
    // 添加筛选参数
    if (genderFilter.value) params.gender = genderFilter.value
    if (ageFilter.value) params.age = ageFilter.value
    if (languageFilter.value) params.language = languageFilter.value
    
    const response = await apiRequest('/aiAvatar/voiceList', {
      method: 'GET',
      params
    })

    if (response && response.code === 200 && response.data) {
      const { data, total } = response.data
      
      // 初始化播放状态
      const processedData = data.map(voice => ({
        ...voice,
        isPlaying: false
      }))
      
      if (isLoadMore) {
        voiceList.value = [...voiceList.value, ...processedData]
      } else {
        voiceList.value = processedData
      }

      // 判断是否还有更多数据
      voiceHasMore.value = voiceList.value.length < total
      if (voiceHasMore.value) {
        voicePageNo.value++
      }
    }
  } catch (error) {
    console.error('获取AI音色列表失败:', error)
    ElMessage.warning('获取AI音色列表失败')
  } finally {
    voiceLoading.value = false
  }
}

// 处理数字人列表滚动
function handleAvatarScroll(e) {
  const { scrollHeight, scrollTop, clientHeight } = e.target
  // 滚动到底部时加载更多
  if (scrollHeight - scrollTop - clientHeight < 50 && !avatarLoading.value && avatarHasMore.value) {
    getAvatarList(true)
  }
}

// 处理音色列表滚动
function handleVoiceScroll(e) {
  const { scrollHeight, scrollTop, clientHeight } = e.target
  // 滚动到底部时加载更多
  if (scrollHeight - scrollTop - clientHeight < 50 && !voiceLoading.value && voiceHasMore.value) {
    getVoiceList(true)
  }
}

// 选择数字人
function handleSelectAvatar(avatar) {
  console.log('选择数字人:', avatar.aiavatarName, avatar.aiavatarId)
  selectedAvatar.value = avatar
  console.log('selectedAvatar设置后:', selectedAvatar.value)
}

// 确认数字人选择
function confirmAvatarSelection() {
  console.log('确认选择时的selectedAvatar:', selectedAvatar.value)
  if (selectedAvatar.value) {
    formData.digitalHuman = selectedAvatar.value
    console.log('设置formData.digitalHuman:', formData.digitalHuman)
    showAvatarDialog.value = false
  } else {
    ElMessage.warning('请选择一个数字人')
  }
}

// 播放数字人预览
function handlePlayPreview(avatar) {
  // 先选中数字人
  handleSelectAvatar(avatar)
  
  // 然后播放视频
  const videoEl = document.querySelector(`video[src="${avatar.previewVideoUrl}"]`)
  if (videoEl) {
    if (videoEl.paused) {
      // 暂停其他所有视频
      document.querySelectorAll('.avatar-video').forEach(video => {
        if (video !== videoEl) {
          video.pause()
          video.currentTime = 0
        }
      })
      // 播放当前视频
      videoEl.play().catch(console.error)
    } else {
      videoEl.pause()
      videoEl.currentTime = 0
    }
  }
}

// 选择音色
function handleSelectVoice(voice) {
  selectedVoice.value = voice
}

// 确认音色选择
function confirmVoiceSelection() {
  if (selectedVoice.value) {
    formData.voice = selectedVoice.value
    closeVoiceDialog()
  } else {
    ElMessage.warning('请选择一个音色')
  }
}

// 关闭音色弹窗
function closeVoiceDialog() {
  // 停止音频播放
  stopAllVoicePlayback()
  showVoiceDialog.value = false
}

// 停止所有音色播放
function stopAllVoicePlayback() {
  try {
    // 先重置所有音色的播放状态
    voiceList.value.forEach(voice => {
      voice.isPlaying = false
    })
    
    // 如果音频正在播放，先暂停
    if (!audioPlayer.value.paused) {
      audioPlayer.value.pause()
    }
    
    // 重置播放位置
    audioPlayer.value.currentTime = 0
    
    // 清空音频源
    audioPlayer.value.src = ''
    
    // 移除事件监听器，避免触发错误回调
    audioPlayer.value.onended = null
    audioPlayer.value.onerror = null
    
  } catch (error) {
    // 静默处理错误，避免在控制台显示错误信息
    console.log('音频停止过程中的预期行为:', error.message)
  }
}

// 播放音色示例
function playVoiceDemo(voice) {
  try {
    // 如果没有试听音频URL，提示错误
    if (!voice.demoAudioUrl) {
      ElMessage.warning('该音色暂无试听音频')
      return
    }
    
    // 如果音频正在播放且是当前音色，则暂停
    if (audioPlayer.value.src === voice.demoAudioUrl && !audioPlayer.value.paused) {
      audioPlayer.value.pause()
      return
    }
    
    // 停止当前播放
    if (!audioPlayer.value.paused) {
      audioPlayer.value.pause()
    }
    
    // 设置新的音频源并播放
    audioPlayer.value.src = voice.demoAudioUrl
    audioPlayer.value.play().catch(error => {
      console.error('音频播放失败:', error)
      ElMessage.error('音频播放失败')
    })
    
  } catch (error) {
    console.error('音频播放过程出错:', error)
    ElMessage.error('音频播放失败')
  }
}

// 处理音色筛选变化
function handleVoiceFilterChange() {
  getVoiceList(false)
}

// 监听筛选条件变化
watch([genderFilter, activeEthnicity], () => {
  getAvatarList()
  getVoiceList()
})

// 监听音色弹窗关闭
watch(showVoiceDialog, (newVal) => {
  if (!newVal) {
    // 延迟停止音频，避免在弹窗关闭动画过程中停止导致的错误
    setTimeout(() => {
      stopAllVoicePlayback()
    }, 100)
  }
})

// 组件卸载时清理
onUnmounted(() => {
  try {
    // 清理音频播放器
    if (audioPlayer.value) {
      // 移除事件监听器
      audioPlayer.value.onended = null
      audioPlayer.value.onerror = null
      
      // 暂停播放
      if (!audioPlayer.value.paused) {
  audioPlayer.value.pause()
      }
      
      // 清空源
  audioPlayer.value.src = ''
    }
    
    // 清理视频播放器
  Object.values(previewVideoRefs.value).forEach(videoEl => {
    if (videoEl) {
        try {
      videoEl.pause()
      videoEl.src = ''
        } catch (error) {
          // 静默处理视频清理错误
          console.log('视频清理过程中的预期行为')
        }
    }
  })
  } catch (error) {
    // 静默处理清理过程中的错误
    console.log('组件卸载清理过程中的预期行为')
  }
})

// 页面加载时获取数据
onMounted(() => {
  getEthnicityList()
  getAvatarList()
  getVoiceList()
})

// 获取上传凭证
const getUploadCredentials = async () => {
  try {
    const response = await apiRequest(API_CONFIG.ENDPOINTS.GET_UPLOAD_CREDENTIAL, {
      method: 'GET'
    })
    
    if (response.code === 200) {
      const { uploadUrl, fileId, fileName } = response.data
      return { uploadUrl, fileId, fileName }
    } else {
      ElMessage.error('获取上传凭证失败')
      throw new Error(response.message || '获取上传凭证失败')
    }
  } catch (error) {
    console.error('获取上传凭证失败:', error)
    ElMessage.error('获取上传凭证失败')
    throw error
  }
}

// 获取文件状态显示文本
const getFileStatus = (file) => {
  if (file.error) {
    return '上传失败'
  }
  if (file.uploading) {
    return '上传中...'
  }
  if (file.fileId) {
    return '上传成功'
  }
  return '等待上传'
}

// 重试上传
const retryUpload = async (file) => {
  // 重置文件状态
  file.uploading = true
  file.uploadProgress = 0
  file.error = false
  file.fileId = null

  let progressInterval = null

  try {
    console.log('重试上传文件:', file.name)
    
    // 启动虚拟进度条
    progressInterval = setInterval(() => {
      if (file.uploadProgress < 85 && file.uploading) {
        file.uploadProgress += Math.random() * 3 + 1
        file.uploadProgress = Math.min(85, Math.floor(file.uploadProgress))
      }
    }, 500)
    
    // 获取上传凭证
    const { uploadUrl, fileId, fileName } = await getUploadCredentials()
    
    // 上传到S3
    await axios.put(uploadUrl, file.raw, {
      headers: {
        'Content-Type': file.raw.type
      }
    })

    // 清除虚拟进度条
    clearInterval(progressInterval)
    
    // 更新文件信息
    file.fileId = fileId
    file.s3Url = uploadUrl.split('?')[0]
    file.uploading = false
    file.uploadProgress = 100

    ElMessage.success('重试上传成功')
  } catch (error) {
    console.error('重试上传失败:', error)
    if (progressInterval) {
      clearInterval(progressInterval)
    }
    file.error = true
    file.uploading = false
    ElMessage.error('重试上传失败')
  }
}

// 修改 handleVideoChange 函数
const handleVideoChange = async (file, fileList) => {
  console.log('handleVideoChange 被调用:', { file, fileList })
  
  if (!file.raw.type.startsWith('video/') && !file.raw.type.startsWith('image/')) {
    ElMessage.error('请选择视频或图片文件')
    // 清除上传组件中的文件
    if (uploadRef.value) {
      uploadRef.value.clearFiles()
    }
    return false
  }

  // 检查文件大小 (500MB)
  const maxSize = 500 * 1024 * 1024
  if (file.raw.size > maxSize) {
    ElMessage.error('文件大小不能超过500MB')
    if (uploadRef.value) {
      uploadRef.value.clearFiles()
    }
    return false
  }

  // 创建响应式文件对象
  const reactiveFile = reactive({
    uid: file.uid,
    name: file.name,
    raw: file.raw,
    uploading: true,
    uploadProgress: 0,
    error: false,
    fileId: null,
    s3Url: null,
    url: null
  })

  // 手动添加文件到 videoList
  videoList.value.push(reactiveFile)

  // 清除上传组件中的文件列表，防止重复显示和状态混乱
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }

  let progressInterval = null

  try {
    // 创建本地预览URL
    const localPreviewUrl = URL.createObjectURL(reactiveFile.raw)
    reactiveFile.url = localPreviewUrl
    
    console.log('开始上传，初始状态:', { uploading: reactiveFile.uploading, progress: reactiveFile.uploadProgress })
    
    // 启动虚拟进度条
    progressInterval = setInterval(() => {
      if (reactiveFile.uploadProgress < 85 && reactiveFile.uploading) {
        reactiveFile.uploadProgress += Math.random() * 3 + 1
        reactiveFile.uploadProgress = Math.min(85, Math.floor(reactiveFile.uploadProgress))
        console.log('进度更新:', reactiveFile.uploadProgress)
      }
    }, 500)
    
    // 获取上传凭证
    const { uploadUrl, fileId, fileName } = await getUploadCredentials()
    
    // 上传到S3
    await axios.put(uploadUrl, reactiveFile.raw, {
      headers: {
        'Content-Type': reactiveFile.raw.type
      }
    })

    // 清除虚拟进度条
    clearInterval(progressInterval)
    
    // 更新文件信息
    reactiveFile.fileId = fileId
    reactiveFile.s3Url = uploadUrl.split('?')[0]
    reactiveFile.uploading = false
    reactiveFile.uploadProgress = 100

    console.log('上传完成，最终状态:', { uploading: reactiveFile.uploading, progress: reactiveFile.uploadProgress, fileId: reactiveFile.fileId })

    ElMessage.success('上传成功')
  } catch (error) {
    console.error('上传失败:', error)
    // 清除虚拟进度条
    if (progressInterval) {
      clearInterval(progressInterval)
    }
    reactiveFile.error = true
    reactiveFile.uploading = false
    ElMessage.error('上传失败')
  }
  return false // 阻止自动上传
}

// 处理上传成功
const handleUploadSuccess = (response, file) => {
  // 由于我们使用自定义上传，这个函数可能不会被调用
  console.log('Upload success:', response, file)
}

// 处理上传失败
const handleUploadError = (err, file) => {
  console.error('Upload error:', err)
  ElMessage.error('上传失败')
  // 从列表中移除失败的文件
  const index = videoList.value.indexOf(file)
  if (index !== -1) {
    videoList.value.splice(index, 1)
    if (file.url) {
      URL.revokeObjectURL(file.url)
    }
  }
}

// 处理视频文件移除
const handleVideoRemove = (file) => {
  const index = videoList.value.indexOf(file)
  if (index !== -1) {
    videoList.value.splice(index, 1)
    if (file.url) {
      URL.revokeObjectURL(file.url)
    }
  }
}

// 处理提交
const handleSubmit = async () => {
  if (!formData.productName) {
    ElMessage.warning('请输入产品名称')
    return
  }
  if (!formData.productFeatures) {
    ElMessage.warning('请输入产品特点')
    return
  }
  if (videoList.value.length === 0) {
    ElMessage.warning('请上传视频素材')
    return
  }

  // 检查是否有上传成功的文件
  const successFiles = videoList.value.filter(file => file.fileId)
  if (successFiles.length === 0) {
    ElMessage.warning('请等待文件上传完成')
    return
  }

  submitting.value = true
  try {
    // 准备请求参数
    const requestData = {
      fileIds: successFiles.map(file => file.fileId),
      productName: formData.productName,
      productDescription: formData.productFeatures
    }

    // 添加可选参数
    if (formData.digitalHuman && formData.digitalHuman.aiavatarId) {
      requestData.aiavatarId = formData.digitalHuman.aiavatarId
    }
    
    if (formData.voice && formData.voice.voiceId) {
      requestData.voiceId = formData.voice.voiceId
    }

    console.log('提交视频混剪任务，参数:', requestData)

    const response = await apiRequest('/m2v/task/create', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    })

    if (response && response.code === 200) {
      ElMessage.success('任务创建成功，正在生成视频...')
      console.log('任务创建成功:', response.data)
      
      // 跳转到列表页面
      router.push('/video-mix/list')
    } else {
      console.error('创建任务失败:', response)
      ElMessage.error(response?.message || '创建任务失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 处理取消
const handleCancel = () => {
  router.back()
}

// 处理视频预览鼠标悬停
const handlePreviewMouseOver = (file) => {
  const videoEl = previewVideoRefs.value[file.uid]
  if (videoEl) {
    videoEl.play().catch(() => {})
    file.isPlaying = true
  }
}

// 处理视频预览鼠标移出
const handlePreviewMouseOut = (file) => {
  const videoEl = previewVideoRefs.value[file.uid]
  if (videoEl) {
    videoEl.pause()
    file.isPlaying = false
  }
}

// 切换视频播放状态
const togglePreviewPlay = (file) => {
  const videoEl = previewVideoRefs.value[file.uid]
  if (!videoEl) return

  if (file.isPlaying) {
    videoEl.pause()
    file.isPlaying = false
  } else {
    videoEl.play().catch(() => {})
    file.isPlaying = true
  }
}

// 处理图片预览
const handlePreviewImage = (file) => {
  currentPreviewFile.value = file
  previewImageVisible.value = true
}

// 处理数字人选择弹窗
const openAvatarDialog = () => {
  // 设置当前已选择的数字人为选中状态
  if (formData.digitalHuman) {
    selectedAvatar.value = formData.digitalHuman
    console.log('弹窗打开，设置当前选中:', formData.digitalHuman.aiavatarName)
  } else {
    selectedAvatar.value = null
    console.log('弹窗打开，没有已选择的数字人')
  }
  showAvatarDialog.value = true
}

// 处理视频播放
function playVideo(avatar) {
  // 先选中数字人
  handleSelectAvatar(avatar)
  
      // 暂停其他所有视频
  avatarList.value.forEach(item => {
    if (item.aiavatarId !== avatar.aiavatarId) {
      item.isPlaying = false
        }
      })
  
      // 播放当前视频
  avatar.isPlaying = true
  
  // 等待DOM更新后播放视频
  setTimeout(() => {
    const videoEl = previewVideoRefs[avatar.aiavatarId]
    if (videoEl) {
      videoEl.play().catch(error => {
        console.error('视频播放失败:', error)
        avatar.isPlaying = false
      })
    }
  }, 100)
}

// 获取人种列表
async function getEthnicityList() {
  try {
    ethnicityLoading.value = true
    const params = new URLSearchParams({
      scene: 'video_avatar'
    })
    
    const response = await apiRequest(`${API_CONFIG.ENDPOINTS.GET_ETHNICITY_LIST}?${params.toString()}`, {
      method: 'GET'
    })
    
    if (response && response.code === 200 && response.result && response.result.data) {
      // 英文到中文的翻译映射
      const ethnicityTranslations = {
        'Black or African American': '非洲裔美国人',
        'White (Western European)': '西欧白人',
        'White (Eastern European)': '东欧白人',
        'Hispanic or Latino': '西班牙裔/拉丁裔',
        'Middle Eastern or North African': '中东/北非',
        'East Asian': '东亚',
        'Southeast Asian': '东南亚',
        'South Asian': '南亚'
      }
      
      // 处理数据并翻译为中文
      ethnicityList.value = response.result.data.map(ethnicity => ({
        ...ethnicity,
        ethnicityName: ethnicityTranslations[ethnicity.ethnicityName] || ethnicity.ethnicityName
      }))
      
      // 设置默认选中"所有"
      if (!activeEthnicity.value) {
        activeEthnicity.value = 'all'
      }
    }
  } catch (error) {
    console.error('获取人种列表失败:', error)
    ElMessage.warning('获取人种列表失败')
  } finally {
    ethnicityLoading.value = false
  }
}

// 处理人种切换
function handleEthnicityChange(ethnicityId) {
  console.log('切换人种:', ethnicityId)
  activeEthnicity.value = ethnicityId
  // 重新获取该人种下的数字人列表
  getAvatarList()
}

// 处理视频播放
function pauseVideo(avatar) {
  // 先选中数字人
  handleSelectAvatar(avatar)
  
  // 然后暂停视频
  const videoEl = previewVideoRefs[avatar.aiavatarId]
  if (videoEl) {
      videoEl.pause()
    avatar.isPlaying = false
  }
}

// 处理视频加载
function onVideoLoaded(avatar) {
  avatar.showCover = false
}

// 处理图片错误
function onImageError(event, avatar) {
  console.error('图片加载失败:', event)
  ElMessage.error('图片加载失败')
  avatar.error = true
}

// 跳转到生成记录页面
function handleGoToRecords() {
  router.push('/video-mix/list')
}
</script>

<style scoped>
.video-mix-generate {
  min-height: 100vh;
  background: #18181c;
  padding: 16px;
  color: #fff;
}

.header {
  margin-bottom: 24px;
}

.section-header {
  display: flex;
  justify-content: flex-start;
  align-items: baseline;
  gap: 32px;
  padding-bottom: 16px;
  border-bottom: 1px solid #2a2a2a;
}

.header .section-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #fff;
  letter-spacing: 0.5px;
  line-height: 1.2;
}

.records-title {
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  color: #409eff;
  position: relative;
  padding: 4px 12px;
  border-radius: 6px;
  background: rgba(64, 158, 255, 0.1);
  border: 1px solid rgba(64, 158, 255, 0.3);
  font-size: 24px;
  font-weight: 600;
  line-height: 1.2;
  margin: 0;
}

.records-title:hover {
  color: #66b1ff;
  background: rgba(64, 158, 255, 0.2);
  border-color: rgba(64, 158, 255, 0.5);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

.records-title::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 12px;
  right: 12px;
  height: 2px;
  background: #409eff;
  transform: scaleX(0);
  transition: transform 0.3s ease;
}

.records-title:hover::after {
  transform: scaleX(1);
}

.main-content {
  max-width: 1800px;
  margin: 0 auto;
  padding: 0 4px;
}

.section {
  background: #23232a;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  border: 1px solid #2a2a2a;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #fff;
  margin: 0 0 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #2a2a2a;
}

.form-content {
  max-width: 100%;
  margin: 0 auto;
}

.upload-content {
  margin-top: 16px;
  max-width: 100%;
  margin: 0 auto;
}

.preview-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.video-card {
  background: #23232a;
  border-radius: 12px;
  overflow: hidden;
  border: 1px solid #2a2a2a;
  transition: all 0.3s ease;
  position: relative;
}

.video-card:hover {
  transform: translateY(-2px);
  border-color: #409eff;
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.2);
}

.video-thumbnail {
  position: relative;
  width: 100%;
  height: 180px;
  background: #18181c;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.video-card:hover .preview-video {
  transform: scale(1.05);
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #fff;
  font-size: 14px;
}

.video-overlay.error-overlay {
  background: rgba(245, 108, 108, 0.8);
}

.video-overlay.success-overlay {
  background: rgba(103, 194, 58, 0.8);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.video-card:hover .video-overlay.success-overlay {
  opacity: 1;
}

.upload-text,
.error-text {
  font-size: 12px;
  margin-top: 8px;
}

.error-icon,
.success-icon {
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));
}

.video-info {
  padding: 16px;
  background: #23232a;
}

.video-name {
  font-size: 14px;
  color: #fff;
  font-weight: 500;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.4;
}

.video-status {
  font-size: 12px;
  color: #909399;
}

.video-status.uploading {
  color: #e6a23c;
}

.video-status.success {
  color: #67c23a;
}

.video-status.error {
  color: #f56c6c;
}

.video-actions {
  padding: 12px 16px;
  border-top: 1px solid #2a2a2a;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  background: #1f1f1f;
}

.select-trigger {
  background: #18181c;
  border: 1px solid #2a2a2a;
  border-radius: 8px;
  padding: 12px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.select-trigger:hover {
  border-color: #409eff;
  background: #23232a;
}

.selected-option {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #fff;
}

.placeholder {
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #909399;
}

.digital-human-grid {
  min-height: 200px;
}

.digital-human-card {
  background: #18181c;
  border: 1px solid #2a2a2a;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 16px;
}

.digital-human-card:hover {
  border-color: #409eff;
  transform: translateY(-2px);
}

.digital-human-card.active {
  border-color: #409eff;
  background: #23232a;
}

.digital-human-avatar {
  width: 64px;
  height: 64px;
  border-radius: 50%;
  object-fit: cover;
}

.digital-human-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.digital-human-info .name {
  font-size: 16px;
  font-weight: 500;
  color: #fff;
}

.digital-human-info .description {
  font-size: 14px;
  color: #909399;
}

.voice-list {
  min-height: 200px;
}

.voice-item {
  background: #18181c;
  border: 1px solid #2a2a2a;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.voice-item:hover {
  border-color: #409eff;
  transform: translateY(-2px);
}

.voice-item.active {
  border-color: #409eff;
  background: #23232a;
}

.voice-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.voice-info .name {
  font-size: 16px;
  font-weight: 500;
  color: #fff;
}

.voice-info .description {
  font-size: 14px;
  color: #909399;
}

.actions {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 24px;

  .generate-btn {
    position: relative;
    padding-right: 80px !important;

    .points-text {
      position: absolute;
      right: 12px;
      top: 50%;
      transform: translateY(-50%);
      font-size: 12px;
      opacity: 1;
      padding-left: 12px;
      border-left: 1px solid rgba(255, 255, 255, 0.5);
    }
  }
}

.full-width {
  width: 100%;
}

/* Element Plus 暗色主题覆盖 */
:deep(.el-input__wrapper) {
  background: #18181c !important;
  box-shadow: 0 0 0 1px #2a2a2a inset !important;
  border-radius: 8px !important;
  padding: 0 16px !important;
  height: 48px !important;
  transition: all 0.3s ease !important;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #409eff inset !important;
  background: #23232a !important;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset !important;
  background: #23232a !important;
}

:deep(.el-input__inner) {
  color: #fff !important;
  font-size: 14px !important;
  height: 48px !important;
}

:deep(.el-textarea__inner) {
  background: #18181c !important;
  border: 1px solid #2a2a2a !important;
  border-radius: 8px !important;
  color: #fff !important;
  padding: 16px !important;
  font-size: 14px !important;
  min-height: 120px !important;
  transition: all 0.3s ease !important;
}

:deep(.el-textarea__inner:hover) {
  border-color: #409eff !important;
  background: #23232a !important;
}

:deep(.el-textarea__inner:focus) {
  border-color: #409eff !important;
  background: #23232a !important;
}

:deep(.el-form-item__label) {
  color: #fff !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  margin-bottom: 8px !important;
  padding: 0 !important;
}

:deep(.el-form-item) {
  margin-bottom: 24px !important;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0 !important;
}

:deep(.el-input__prefix) {
  color: #909399 !important;
}

:deep(.el-input__suffix) {
  color: #909399 !important;
}

:deep(.el-input__count) {
  background: transparent !important;
  color: #909399 !important;
}

:deep(.el-textarea__count) {
  background: transparent !important;
  color: #909399 !important;
}

:deep(.el-select .el-input__wrapper) {
  background: #18181c !important;
  box-shadow: 0 0 0 1px #2a2a2a inset !important;
}

:deep(.el-select .el-input__inner) {
  color: #fff !important;
}

:deep(.el-select-dropdown) {
  background: #23232a !important;
  border: 1px solid #2a2a2a !important;
}

:deep(.el-select-dropdown__item) {
  color: #fff !important;
}

:deep(.el-select-dropdown__item.hover) {
  background: #18181c !important;
}

:deep(.el-select-dropdown__item.selected) {
  color: #409eff !important;
  background: #18181c !important;
}

:deep(.el-upload-dragger) {
  background: #18181c !important;
  border: 1px dashed #2a2a2a !important;
  width: 100% !important;
  height: auto !important;
  padding: 20px !important;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409eff !important;
}

:deep(.el-upload-dragger .el-icon) {
  color: #409eff !important;
  font-size: 48px !important;
  margin-bottom: 16px !important;
}

:deep(.el-upload-dragger .el-upload__text) {
  color: #fff !important;
  margin: 0 !important;
}

:deep(.el-upload-dragger .el-upload__text em) {
  color: #409eff !important;
}

:deep(.el-upload-list) {
  background: transparent !important;
  border: none !important;
  padding: 0 !important;
  margin-top: 16px !important;
}

:deep(.el-upload-list__item) {
  color: #fff !important;
  background: #23232a !important;
  border: 1px solid #2a2a2a !important;
  border-radius: 8px !important;
  margin-top: 8px !important;
}

:deep(.el-upload-list__item:hover) {
  background: #2a2a2a !important;
}

:deep(.el-upload-list__item-name) {
  color: #fff !important;
}

:deep(.el-upload-list__item-status-label) {
  color: #909399 !important;
}

:deep(.el-upload-list__item .el-icon) {
  color: #909399 !important;
}

:deep(.el-dialog) {
  background: #23232a !important;
  border: 1px solid #2a2a2a !important;
}

:deep(.el-dialog__title) {
  color: #fff !important;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #2a2a2a !important;
}

:deep(.el-dialog__body) {
  color: #fff !important;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #2a2a2a !important;
}

:deep(.el-message) {
  background: #23232a !important;
  border: 1px solid #2a2a2a !important;
  color: #fff !important;
}

:deep(.el-message--success) {
  background: #23232a !important;
  border-color: #67c23a !important;
}

:deep(.el-message--warning) {
  background: #23232a !important;
  border-color: #e6a23c !important;
}

:deep(.el-message--error) {
  background: #23232a !important;
  border-color: #f56c6c !important;
}

:deep(.el-message--info) {
  background: #23232a !important;
  border-color: #909399 !important;
}

:deep(.selection-dialog .el-dialog__body) {
  padding: 0 20px 20px;
}

:deep(.selection-dialog .el-dialog__header) {
  padding: 20px;
  margin: 0;
}

:deep(.el-loading-mask) {
  background: rgba(24, 24, 28, 0.8) !important;
}

:deep(.el-loading-spinner .circular) {
  color: #409eff !important;
}

/* 数字人选择弹窗样式 */
:deep(.avatar-dialog) {
  background: transparent !important;
}

:deep(.avatar-dialog .el-overlay) {
  background-color: rgba(0, 0, 0, 0.7) !important;
}

:deep(.avatar-dialog .el-dialog) {
  background: #23232a;
  border: 1px solid #2a2a2a;
  border-radius: 12px;
  margin: 0 !important;
}

:deep(.avatar-dialog .el-dialog__header) {
  background: #2a2a2a;
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #32323a;
  position: relative;
}

:deep(.avatar-dialog .el-dialog__title) {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
}

:deep(.avatar-dialog .el-dialog__body) {
  padding: 20px;
  background: #23232a;
  color: #fff;
}

:deep(.avatar-dialog .el-dialog__footer) {
  background: #23232a;
  border-top: 1px solid #32323a;
  padding: 16px 20px;
}

/* 数字人弹窗关闭按钮样式调整 */
:deep(.avatar-dialog .el-dialog__headerbtn) {
  top: 24px !important;
  right: 24px !important;
  width: 32px !important;
  height: 32px !important;
  background: rgba(255, 255, 255, 0.1) !important;
  border-radius: 6px !important;
  transition: all 0.3s ease !important;
}

:deep(.avatar-dialog .el-dialog__headerbtn:hover) {
  background: rgba(255, 255, 255, 0.2) !important;
}

:deep(.avatar-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: #fff !important;
  font-size: 16px !important;
  font-weight: bold !important;
}

.avatar-filter {
  margin-bottom: 20px;
  display: flex;
  gap: 20px;
  background: #2a2a2a;
  padding: 16px;
  border-radius: 8px;
}

.ethnicity-filter {
  flex: 1;
}

.filter-label {
  color: #e0e0e0;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 12px;
  display: block;
}

.ethnicity-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.ethnicity-item {
  padding: 6px 12px;
  background: #18181c;
  border: 1px solid #409eff;
  border-radius: 16px;
  color: #ffffff;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: #409eff;
    color: #fff;
    transform: translateY(-1px);
  }

  &.active {
    background: #409eff;
    color: #fff;
  }

  &.disabled {
    cursor: not-allowed;
    opacity: 0.6;
    color: #666666;
    border-color: #333333;
    background: #18181c;

    &:hover {
      transform: none;
      background: #18181c;
      color: #666666;
    }
  }
}

.avatar-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  max-height: 60vh;
  overflow-y: auto;
  padding: 16px;
  background: #18181c;
  border-radius: 8px;
}

.avatar-card {
  background: #23232a;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #2a2a2a;
  color: #fff;
}

.avatar-card:hover {
  background: #2a2a2a;
  border-color: #409eff;
  transform: translateY(-2px);
}

.avatar-card.active {
  background: #2a2a2a;
  border-color: #409eff;
}

.avatar-image-wrapper {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
  border-radius: 8px;
  margin-bottom: 12px;
  background: #18181c;
}

.avatar-video {
  width: 100%;
  height: 100%;
  object-fit: contain;
  background: #18181c;
}

.avatar-cover {
  width: 100%;
  height: 100%;
  object-fit: cover;
  background: #18181c;
  cursor: pointer;
  transition: transform 0.3s ease;
}

.avatar-card:hover .avatar-cover {
  transform: scale(1.05);
}

.play-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  cursor: pointer;
}

.avatar-card:hover .play-overlay {
  opacity: 1;
}

.pause-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  cursor: pointer;
}

.avatar-card:hover .pause-overlay {
  opacity: 1;
}

.play-icon,
.pause-icon {
  color: white;
  font-size: 48px;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.5));
}

.avatar-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.avatar-name {
  font-size: 16px;
  font-weight: 500;
  color: #fff;
  margin-bottom: 4px;
}

.avatar-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 加载更多样式 */
.loading-more {
  grid-column: 1 / -1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  color: #909399;
  font-size: 14px;
  gap: 8px;
  background: #2a2a2a;
  border-radius: 8px;
}

/* 滚动条样式 */
.avatar-grid::-webkit-scrollbar {
  width: 6px;
}

.avatar-grid::-webkit-scrollbar-track {
  background: #18181c;
  border-radius: 3px;
}

.avatar-grid::-webkit-scrollbar-thumb {
  background: #409eff;
  border-radius: 3px;
}

/* 音色选择弹窗样式 */
:deep(.voice-dialog) {
  background: transparent !important;
}

:deep(.voice-dialog .el-overlay) {
  background-color: rgba(0, 0, 0, 0.7) !important;
}

:deep(.voice-dialog .el-dialog) {
  background: #23232a;
  border: 1px solid #2a2a2a;
  border-radius: 12px;
  margin: 0 !important;
}

:deep(.voice-dialog .el-dialog__header) {
  background: #2a2a2a;
  margin: 0;
  padding: 20px;
  border-bottom: 1px solid #32323a;
  position: relative;
}

:deep(.voice-dialog .el-dialog__title) {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
}

:deep(.voice-dialog .el-dialog__body) {
  padding: 20px;
  background: #23232a;
  color: #fff;
}

:deep(.voice-dialog .el-dialog__footer) {
  background: #23232a;
  border-top: 1px solid #32323a;
  padding: 16px 20px;
}

/* 音色弹窗关闭按钮样式调整 */
:deep(.voice-dialog .el-dialog__headerbtn) {
  top: 24px !important;
  right: 24px !important;
  width: 32px !important;
  height: 32px !important;
  background: rgba(255, 255, 255, 0.1) !important;
  border-radius: 6px !important;
  transition: all 0.3s ease !important;
}

:deep(.voice-dialog .el-dialog__headerbtn:hover) {
  background: rgba(255, 255, 255, 0.2) !important;
}

:deep(.voice-dialog .el-dialog__headerbtn .el-dialog__close) {
  color: #fff !important;
  font-size: 16px !important;
  font-weight: bold !important;
}

.voice-filter {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
  background: #2a2a2a;
  padding: 24px;
  border-radius: 12px;
  border: 1px solid #32323a;
  flex-wrap: wrap;
}

.filter-item {
  margin-right: 0 !important;
}

.language-select {
  min-width: 220px !important;
}

.voice-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
  max-height: 60vh;
  overflow-y: auto;
  padding: 16px;
  background: #18181c;
  border-radius: 8px;
}

.voice-card {
  background: #23232a;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #2a2a2a;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
}

.voice-card:hover {
  background: #2a2a2a;
  border-color: #409eff;
}

.voice-card.active {
  background: #2a2a2a;
  border-color: #409eff;
}

.voice-info {
  flex: 1;
}

.voice-name {
  font-size: 16px;
  font-weight: 500;
  color: #fff;
  margin-bottom: 8px;
}

.voice-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.voice-preview {
  margin-left: 16px;
}

/* 音色网格滚动条样式 */
.voice-grid::-webkit-scrollbar {
  width: 6px;
}

.voice-grid::-webkit-scrollbar-track {
  background: #18181c;
  border-radius: 3px;
}

.voice-grid::-webkit-scrollbar-thumb {
  background: #409eff;
  border-radius: 3px;
}

/* 单选按钮组样式修复 */
:deep(.voice-dialog .el-radio-button__inner) {
  background-color: #23232a !important;
  border: 1px solid #2a2a2a !important;
  color: #909399 !important;
  box-shadow: none !important;
  font-weight: 500 !important;
  font-size: 14px !important;
  padding: 10px 20px !important;
  margin: 0 8px 0 0 !important;
  border-radius: 8px !important;
  transform: none !important;
  scale: 1 !important;
  zoom: 1 !important;
}

:deep(.voice-dialog .el-radio-button__inner:hover) {
  border-color: #409eff !important;
  color: #409eff !important;
  background-color: #2a2a2a !important;
  transform: none !important;
  scale: 1 !important;
  zoom: 1 !important;
}

:deep(.voice-dialog .el-radio-button.is-active .el-radio-button__inner),
:deep(.voice-dialog .el-radio-button__orig-radio:checked + .el-radio-button__inner) {
  background: linear-gradient(135deg, #409eff, #66b1ff) !important;
  border-color: #409eff !important;
  color: #ffffff !important;
  font-weight: 600 !important;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3) !important;
  transform: none !important;
  scale: 1 !important;
  zoom: 1 !important;
  font-size: 14px !important;
  padding: 10px 20px !important;
}

/* 产品特点输入框专门的样式覆盖 - 去掉白色边框 */
:deep(.el-form-item:nth-child(2) .el-textarea__inner) {
  border: 1px solid #2a2a2a !important;
  background: #18181c !important;
  color: #fff !important;
}

:deep(.el-form-item:nth-child(2) .el-textarea__inner:hover) {
  border-color: #409eff !important;
  background: #23232a !important;
}

:deep(.el-form-item:nth-child(2) .el-textarea__inner:focus) {
  border-color: #409eff !important;
  background: #23232a !important;
  box-shadow: none !important;
  outline: none !important;
}

/* 更通用的产品特点输入框样式覆盖 */
:deep(.el-form-item[data-field="productFeatures"] .el-textarea__inner),
:deep(.form-content .el-form-item:nth-of-type(2) .el-textarea__inner) {
  border: 1px solid #2a2a2a !important;
  background: #18181c !important;
  color: #fff !important;
  box-shadow: none !important;
  outline: none !important;
}

:deep(.el-form-item[data-field="productFeatures"] .el-textarea__inner:hover),
:deep(.form-content .el-form-item:nth-of-type(2) .el-textarea__inner:hover) {
  border-color: #409eff !important;
  background: #23232a !important;
  box-shadow: none !important;
}

:deep(.el-form-item[data-field="productFeatures"] .el-textarea__inner:focus),
:deep(.form-content .el-form-item:nth-of-type(2) .el-textarea__inner:focus) {
  border-color: #409eff !important;
  background: #23232a !important;
  box-shadow: none !important;
  outline: none !important;
}

</style> 